{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import os\n",
    "\n",
    "\n",
    "def get_frame_from_video(video_name, frame_time, img_name):\n",
    "    \"\"\"\n",
    "    get a specific frame of a video by time in milliseconds\n",
    "    :param video_name: video name, include path\n",
    "    :param frame_time: time of the desired frame\n",
    "    :param img_dir: path which use to store output image\n",
    "    :param img_name: name of output image\n",
    "    :return: None\n",
    "    \"\"\"\n",
    "    vidcap = cv2.VideoCapture(video_name)\n",
    "    # Current position of the video file in milliseconds.\n",
    "    vidcap.set(cv2.CAP_PROP_POS_MSEC, frame_time - 1)\n",
    "    # read(): Grabs, decodes and returns the next video frame\n",
    "    success, image = vidcap.read()\n",
    "\n",
    "    if not os.path.exists(img_dir):\n",
    "        os.makedirs(img_dir)\n",
    "\n",
    "    if success:\n",
    "        # save frame as JPEG file\n",
    "        cv2.imwrite(img_name, image)  \n",
    "    return success"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import re, json\n",
    "# 去掉警告\n",
    "from requests.packages.urllib3.exceptions import InsecureRequestWarning\n",
    "requests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n",
    "\n",
    "\n",
    "class LiveVideoDownload(object):\n",
    "    def __init__(self, up_id, size=10, filename='None.flv'):\n",
    "        self.up_id = up_id\n",
    "        self.size_all = size\n",
    "        self.filename = filename\n",
    "        self.roomIdRegex = r'\"//live\\.bilibili\\.com/{.*?}\"'\n",
    "        self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' + \n",
    "                        'Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362'}\n",
    "    \n",
    "    def getRoomId(self):\n",
    "        url = 'https://api.live.bilibili.com/room/v1/Room/getRoomInfoOld?mid={}'.format(self.up_id)\n",
    "        self.Referer = 'https://space.bilibili.com/{}/'.format(self.up_id)\n",
    "        self.headers['Host'] = 'api.live.bilibili.com'\n",
    "        self.headers['Referer'] = self.Referer\n",
    "        response = requests.get(url=url, headers=self.headers).json()\n",
    "        room_id = response['data']['roomid']\n",
    "        return room_id\n",
    "\n",
    "    def getJsonFile(self, room_id):\n",
    "        url = 'https://api.live.bilibili.com/room/v1/Room/playUrl?cid={}'.format(room_id)\n",
    "        content = requests.get(url=url, headers=self.headers).text\n",
    "        return content\n",
    "       \n",
    "    def extract(self):\n",
    "        room_id = self.getRoomId()\n",
    "        data = self.getJsonFile(room_id)\n",
    "        data_json = json.loads(data)\n",
    "        download_url = data_json['data']['durl'][0]['url']\n",
    "        host = download_url[8:].split('/')[0]\n",
    "        return download_url, host\n",
    "    \n",
    "    def download(self):\n",
    "        content = self.extract()\n",
    "        url, host = content\n",
    "        print(url)\n",
    "        headers = self.headers\n",
    "        headers['host'] = host\n",
    "        headers['referer'] = self.Referer\n",
    "        # 下载\n",
    "        size = 0\n",
    "        chunk_size = 1024\n",
    "        response = requests.get(url, stream=True)\n",
    "#         print(response)\n",
    "        with open(self.filename, 'wb') as file:\n",
    "            for data in response.iter_content(chunk_size = chunk_size):\n",
    "                file.write(data)\n",
    "                size += len(data)/1024/1024\n",
    "                file.flush()\n",
    "                # print('[下载进度]: %.2fMB/%.2fMB' % (size, self.size_all))\n",
    "                if size > self.size_all:  # 一般response的iter_content不大\n",
    "                    break\n",
    "        print('下载完成')\n",
    "                \n",
    "\n",
    "# if __name__ == '__main__':\n",
    "#     up_id = '50333369'  # uid 号\n",
    "#     size_MB = 3 # 下载量为 [size_MB] MB\n",
    "#     filename = 'test.mp4' #下载文件名\n",
    "#     liveVideo = LiveVideoDownload(up_id=up_id, size=size_MB, filename=filename)\n",
    "#     liveVideo.download()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyzbar.pyzbar import decode\n",
    "from PIL import Image,ImageEnhance\n",
    "import os\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "图片包含二维码检测\n",
    "\"\"\"\n",
    "def qrcode_recongnize(filename):\n",
    "    \"\"\"\n",
    "    :param filename: 图片path + name\n",
    "    :return: boolean\n",
    "    \"\"\"\n",
    "    image_type = False\n",
    "    try:\n",
    "        # 读取图片\n",
    "        img = Image.open(filename).convert('RGB')\n",
    "        # 增加亮度\n",
    "        img = ImageEnhance.Brightness(img).enhance(1.0)\n",
    "        # 锐利化\n",
    "        img = ImageEnhance.Sharpness(img).enhance(1.5)\n",
    "        # 增加对比度\n",
    "        img = ImageEnhance.Contrast(img).enhance(2.0)\n",
    "        # 灰度化\n",
    "        img = img.convert('L')\n",
    "        # 解码二维码\n",
    "        result = decode(img)\n",
    "        if len(result)>0:\n",
    "            image_type = True\n",
    "    except:\n",
    "        pass\n",
    "    return image_type\n",
    "\n",
    "\n",
    "# if __name__ == '__main__':\n",
    "#     filepath=\"./img/\"\n",
    "#     for parent, dirnames, filenames in os.walk(filepath):\n",
    "#         for filename in filenames:\n",
    "#             kk=qrcode_recongnize(filepath,filename)\n",
    "#             print(filename, kk)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "https://d1--cn-gotcha03.bilivideo.com/live-bvc/892825/live_280464718_17715596_1500.flv?cdn=cn-gotcha03&expires=1600085131&len=0&oi=3708035787&pt=&qn=150&trid=8029510e175f46ecaaf567d9c2fa7208&sigparams=cdn,expires,len,oi,pt,qn,trid&sign=1831d7a53f51796a672107344a13afb2&ptype=0&src=5&sl=5&order=1\n",
      "下载完成\n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'img_dir' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-6-f76d915a2678>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     10\u001b[0m         \u001b[0mtime\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msleep\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0.5\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     11\u001b[0m         \u001b[0mjpg_name\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34mr'./img/'\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mstr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mcount\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;34m'.jpeg'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 12\u001b[1;33m         \u001b[0msuccess\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mget_frame_from_video\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34mr'test.mp4'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m5\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mjpg_name\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     13\u001b[0m         \u001b[0mtime\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msleep\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0.2\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     14\u001b[0m         \u001b[1;32mif\u001b[0m \u001b[0msuccess\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m<ipython-input-2-74ff4b48b520>\u001b[0m in \u001b[0;36mget_frame_from_video\u001b[1;34m(video_name, frame_time, img_name)\u001b[0m\n\u001b[0;32m     18\u001b[0m     \u001b[0msuccess\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mimage\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mvidcap\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     19\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 20\u001b[1;33m     \u001b[1;32mif\u001b[0m \u001b[1;32mnot\u001b[0m \u001b[0mos\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpath\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mexists\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mimg_dir\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     21\u001b[0m         \u001b[0mos\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmakedirs\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mimg_dir\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     22\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mNameError\u001b[0m: name 'img_dir' is not defined"
     ]
    }
   ],
   "source": [
    "if __name__ == '__main__':\n",
    "    up_id = '280464718'  # uid 号\n",
    "    size_MB = 2 # 下载量为 [size_MB] MB\n",
    "    filename = 'test.mp4' #下载文件名\n",
    "    import time\n",
    "    count = 0\n",
    "    while True:\n",
    "        liveVideo = LiveVideoDownload(up_id=up_id, size=size_MB, filename=filename)\n",
    "        liveVideo.download()\n",
    "        time.sleep(0.5)\n",
    "        jpg_name = r'./img/' + str(count) + '.jpeg'\n",
    "        success = get_frame_from_video(r'test.mp4', 5, jpg_name)\n",
    "        time.sleep(0.2)\n",
    "        if success:\n",
    "            result = qrcode_recongnize(jpg_name)\n",
    "            if result:  # 出现二维码提醒自己去扫码并停止监听\n",
    "                print('检测到视频中出现二维码')\n",
    "                import winsound\n",
    "                winsound.MessageBeep()\n",
    "                winsound.Beep(1000, 5000)  # 主板蜂鸣器, 1000大小持续5秒\n",
    "                break\n",
    "        time.sleep(0.5)\n",
    "        count += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
